package com.devops.admin.service.impl;

import com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenRequest;
import com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenResponseBody;
import com.devops.admin.config.DingTalkConfig;
import com.devops.admin.redis.RedisService;
import com.devops.admin.service.DingTalkService;
import com.devops.constant.DevOpsConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author jxt
 * @Notes
 * @date 2023/3/17 11:23
 */
@Slf4j
@Service
public class DingTalkServiceImpl implements DingTalkService {
    @Resource
    private RedisService redisService;
    @Resource
    private com.aliyun.dingtalkoauth2_1_0.Client dingTalkAuthClient;
    @Resource
    private DingTalkConfig dingTalkConfig;
    @Override
    public String getAccessToken() {
        try {
            if (redisService.hasKey(DevOpsConstant.REDIS_KEY_DINGTALK_ACCESS_TOKEN)) {
                return redisService.get(DevOpsConstant.REDIS_KEY_DINGTALK_ACCESS_TOKEN).toString();
            } else {
                GetAccessTokenRequest getAccessTokenRequest = new GetAccessTokenRequest()
                        .setAppKey(dingTalkConfig.getAppKey())
                        .setAppSecret(dingTalkConfig.getAppSecret());
                GetAccessTokenResponseBody responseBody = dingTalkAuthClient.getAccessToken(getAccessTokenRequest).getBody();
                redisService.set(DevOpsConstant.REDIS_KEY_DINGTALK_ACCESS_TOKEN, responseBody.getAccessToken(), 7100);
                return responseBody.getAccessToken();
            }
        } catch (Exception e) {
            log.error("get dingtalk access_token error {}", e.getMessage());
        }
        return null;
    }
}
